package com.itheima.factory.config_factory;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;
import java.util.logging.Level;

/**
 * @author zzw
 */
public class CoffeeFactory {

    private static final Logger LOGGER = Logger.getLogger(CoffeeFactory.class.getName());

    private static final Map<String, Coffee> MAP = new HashMap<>();

    static {
        Properties p = new Properties();
        InputStream is = CoffeeFactory.class.getResourceAsStream("/bean.properties");
        try {
            p.load(is);
            //遍历Properties集合对象
            Set<Object> keys = p.keySet();
            for (Object key : keys) {
                //根据键获取值（全类名）
                String className = p.getProperty((String) key);
                //获取字节码对象
                Class<?> clazz = Class.forName(className);
                Coffee obj = (Coffee) clazz.getDeclaredConstructor().newInstance();
                MAP.put((String) key, obj);
            }
        }
        catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error initializing CoffeeFactory", e);
        }
        finally {
            // 确保资源被正确关闭
            if (is != null) {
                try {
                    is.close();
                }
                catch (Exception ex) {
                    LOGGER.log(Level.WARNING, "Error closing input stream", ex);
                }
            }
        }
    }

    public static Coffee createCoffee(String name) {
        return MAP.get(name);
    }
}
